//
//  NewsViewController.m
//  Zaker
//
//  Created by 赵磊 on 16/3/7.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "NewsViewController.h"
#import "PchFile.pch"
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapLocation/AMapLocationKit/AMapLocationRegionObj.h>
#import "LunBoTu.h"
#import "CarouselPicture.h"
#import <AFNetworking.h>
#import "LunbotuDetailViewController.h"
#import "SearchViewController.h"
@interface NewsViewController ()<AMapLocationManagerDelegate,CarouselPictureDelegate,UIScrollViewDelegate>
@property (nonatomic, strong) UICollectionView *newsCollectionView;

@property (nonatomic, strong) NSArray *allArr;
@property (nonatomic, strong) NSArray *imgArr;
@property (nonatomic,strong) NSArray *textArr;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, retain)UIView *lunboView;
@property (nonatomic, retain)UIScrollView *photos;//轮播图
@property (nonatomic, retain)NSMutableArray *lunboArr;//存放轮播图图片
@property (nonatomic, retain)NSMutableArray *lunboTitle;//存放轮播图标题
@property (nonatomic, retain)NSMutableArray *lunboId;//详情页需要拼接的id
@property (nonatomic, retain)NSTimer *timer;
@property (nonatomic, retain)UIPageControl *page;
@end

@implementation NewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatNight];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"searchBar_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
    // 设置navigation标题
    self.navigationItem.title = @"新闻";
    self.imgArr = @[@"bagua.png",@"yaowen.png",@"shu.png",@"beike.png",@"picture.png",@"xixi.png"];
    self.textArr = @[@"新闻",@"娱乐",@"科技",@"时尚",@"心理",@"文艺"];
    [self dataHandler];
    [AMapLocationServices sharedServices].apiKey = @"fd46eb6cef4f4b0bf61b259da488366a";
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
//    [self.locationManager startUpdatingLocation];
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间，可修改，最小2s
    self.locationManager.locationTimeout = 3;
    //   逆地理请求超时时间，可修改，最小2s
    self.locationManager.reGeocodeTimeout = 3;
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        
        NSLog(@"location:%@", location);
        
//        if (regeocode)
//        {
//            NSLog(@"reGeocode:%@", regeocode);
//  
//            NSString *city = regeocode.city;
//            [[NSUserDefaults standardUserDefaults] setObject:@"city" forKey:city];
//        }
    }];
}


- (void)createButton
{
    for (int i = 0; i < 3; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(10 * WIDTH * (i + 1) + (SCREEN_WIDTH - 40 * WIDTH) / 3 * i, 250 * HEIGHT, 100 * WIDTH, 100 * HEIGHT);
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 10000 + i;
        [button setBackgroundImage:[UIImage imageNamed:_imgArr[i]] forState:UIControlStateNormal];
        [self.view addSubview:button];
        button.layer.cornerRadius = 100 * HEIGHT / 2;
        button.clipsToBounds = YES;
        

                button.layer.cornerRadius = button.frame.size.width /2;
        button.layer.masksToBounds = YES;
        UILabel *label =[[ UILabel alloc] initWithFrame:CGRectMake(0, 0, (SCREEN_WIDTH - 40 * WIDTH) / 3, 20 * HEIGHT)];
        label.center = CGPointMake((SCREEN_WIDTH - 60 * WIDTH) / 6, (SCREEN_WIDTH - 60 * WIDTH) / 6);
        [button addSubview:label];
        label.text = _textArr[i];
        label.font = [UIFont systemFontOfSize:15 ];
        label.textAlignment = NSTextAlignmentCenter;
        UIButton *secondButton = [UIButton buttonWithType:UIButtonTypeCustom];
        secondButton.frame = CGRectMake(10 * WIDTH * (i + 1) + (SCREEN_WIDTH - 40 * WIDTH) / 3 * i, 390 * HEIGHT, (SCREEN_WIDTH - 60 * WIDTH) / 3, (SCREEN_HEIGHT - 60 * HEIGHT) / 3);
        secondButton.tag = 10003 + i;
        [secondButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [secondButton setBackgroundImage:[UIImage imageNamed:_imgArr[i + 3]] forState:UIControlStateNormal];
        [self.view addSubview:secondButton];
        secondButton.layer.cornerRadius = button.frame.size.width /2;
        secondButton.layer.masksToBounds = YES;
        UILabel *label2 =[[ UILabel alloc] initWithFrame:CGRectMake(0, 0, (SCREEN_WIDTH - 40 * WIDTH) / 3, 20 * HEIGHT)];
        label2.center = CGPointMake((SCREEN_WIDTH - 60 * WIDTH) / 6, (SCREEN_WIDTH - 60 * WIDTH) / 6);
//        label2.backgroundColor = [UIColor redColor];
        [secondButton addSubview:label2];
        label2.text = _textArr[i + 3];
         label2.font = [UIFont systemFontOfSize:15 ];
        label2.textAlignment = NSTextAlignmentCenter;
    }
}
- (void)dataHandler
{
    [LHAFNetworkTool getUrl:@"http://api.app.happyjuzi.com/v2.8.2/article/list/home?net=wifi&page=1&pf=ios&res=320x568&size=20&uid=3931188994231555&ver=2.8.2" body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        NSArray *arr = resposeObject[@"data"][@"info"];
        self.lunboArr = [NSMutableArray array];
        self.lunboTitle = [NSMutableArray array];
        self.lunboId = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            NSString *str = dic[@"pic"];
            NSArray *strArr = [str componentsSeparatedByString:@"!"];
            [self.lunboArr addObject:strArr.firstObject];
            NSString *titlestr = dic[@"title"];
            [self.lunboTitle addObject:titlestr];
            [self.lunboId addObject:dic[@"id"]];
        }
        [self creatLunbo];
        _page.numberOfPages = _lunboArr.count;
        [self handleJudgeNetworkStatus];
         } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
    [LHAFNetworkTool getUrl:@"http://iphone.myzaker.com/zaker/apps_v3.php?_appid=iphone&_version=6.45&act=getAllAppsData" body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        self.allArr = [AllModel modelHandlerWithArray:resposeObject[@"data"][@"datas"]];
        [self createButton];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
    }];
}
#pragma mark - 轮播图的点击方法
//轮播图的点击方法
-(void)pushWithUrl:(NSInteger)num
{
    LunbotuDetailViewController *detail = [[LunbotuDetailViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:detail];
    NSNumber *number = _lunboId[num];
    NSString *path = [NSString stringWithFormat:@"http://api.app.happyjuzi.com/v2.8.2/article/detail?id=%ld&net=wifi&pf=ios&res=320x568&uid=3931188994231555&ver=2.8.2", number.integerValue];
    //解析详情页数据
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:path parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //
        NSDictionary *dic = responseObject[@"data"][@"info"];
        NSString *ss = dic[@"shareurl"];
        detail.pathstr = ss;
        //跳转
        //用push会把前面页的tabbar都带上 所以要用present
        [self presentViewController:nav animated:YES completion:^{
            
        }];
        NSLog(@"%@", responseObject);
        //网络判断
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
    
}

#pragma mark - 点击轮播图
//点击轮播图详情
-(void)tapAction
{
    LunbotuDetailViewController *detail = [[LunbotuDetailViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:detail];
    
    NSNumber *num = _lunboId[_page.currentPage];
    NSString *path = [NSString stringWithFormat:@"http://api.app.happyjuzi.com/v2.8.2/article/detail?id=%ld&net=wifi&pf=ios&res=320x568&uid=3931188994231555&ver=2.8.2", (long)num.integerValue];
    //解析详情页数据
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:path parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //
        NSDictionary *dic = responseObject[@"data"][@"info"];
        NSString *ss = dic[@"shareurl"];
        detail.pathstr = ss;
        //跳转
        [self presentViewController:nav animated:YES completion:^{
            
        }];
        NSLog(@"%@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
 
}

- (void)creatLunbo
{
    self.lunboView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 240 * HEIGHT)];
    [self.view addSubview:_lunboView];
    _lunboView.backgroundColor = [UIColor whiteColor];
    //创建轮播图对象
    CarouselPicture *b = [[CarouselPicture alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 240 * HEIGHT) timeInterval:2 imageUrlArr:_lunboArr urlArr:nil titleArr:_lunboTitle];
    b.delegate = self;
    b.backgroundColor = [UIColor whiteColor];
    [_lunboView addSubview:b];
   }

- (void)buttonAction:(UIButton *)button
{
    AllViewController *allVC = [[AllViewController alloc] init];
    switch (button.tag) {
        case 10000:
        {
            AllModel *m = _allArr[0];
            allVC.allArr = m.sons;
        }
            break;
        case 10001:
        {
            AllModel *m = _allArr[1];
            allVC.allArr = m.sons;
        }
            break;
            case 10002:
        {
            AllModel *m = _allArr[2];
            allVC.allArr = m.sons;
        }
            break;
        case 10003:
        {
            AllModel *m = _allArr[4];
            allVC.allArr = m.sons;
        }
            break;
        case 10004:
        {
            AllModel *m = _allArr[8];
            allVC.allArr = m.sons;
        }
        case 10005:
        {
            AllModel *m = _allArr[12];
            allVC.allArr = m.sons;
        }
            break;
        default:
            break;
    }
    [self.navigationController pushViewController:allVC animated:YES];
}

#pragma mark - 夜间模式
- (void)creatNight
{
    //监听中心,监听后面发来的信息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColor:) name:@"change" object:nil];
    
    //从night中取出储存的字符串(yes,no)
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *passWord = [user objectForKey:@"night"];
    
    if ([passWord isEqualToString:@"yes"]) {
        self.view.backgroundColor = [UIColor colorWithRed:0 / 255. green:30 / 255. blue:60 / 255. alpha:1];
    } else {
        self.view.backgroundColor = [UIColor whiteColor];
    }
}

#pragma mark - defaultCenter方法
- (void)changeColor:(NSNotification *)center
{
    self.view.backgroundColor = [UIColor colorWithRed:0 / 255. green:30 / 255. blue:60 / 255. alpha:1];
    
    //找到字符串
    NSString *passWord = [center object];
    
    //消息中心发出消息NSUserDefaults将object中的字符串存入night中
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:passWord forKey:@"night"];
    
    //判断是yes还是no,yes的话改变背景颜色
    if ([passWord isEqualToString:@"no"]) {
        self.view.backgroundColor = [UIColor whiteColor];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}
#pragma mark -搜索方法
-(void)searchAction
{
    NSLog(@"搜~");
    SearchViewController *searchVc =[[SearchViewController alloc ]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:searchVc];
    searchVc.dingyueArr = _allArr;
    [self presentViewController:nav animated:YES completion:^{
        //
    }];
   
}

#pragma mark - 当前网络判断
- (void)handleJudgeNetworkStatus {
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
                
            case AFNetworkReachabilityStatusUnknown: // 未知网络
            {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前为未知网络" preferredStyle:UIAlertControllerStyleAlert];
                /* 创建action对象 */
                UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    
                }];
                
                /* alert添加action对象 */
                [alert addAction:actionConfirm];
                
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
                
                break;
                
            }
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
            {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"网络连接已断开！" preferredStyle:UIAlertControllerStyleAlert];
                /* 创建action对象 */
                UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    
                }];
                
                /* alert添加action对象 */
                [alert addAction:actionConfirm];
                
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
                
                break;
                
            }
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
            {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"正在使用手机3G/4G网" preferredStyle:UIAlertControllerStyleAlert];
                /* 创建action对象 */
                UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    
                }];
                
                /* alert添加action对象 */
                [alert addAction:actionConfirm];
                
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
                
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
            {
                //                NSLog(@"WIFI");
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"正在使用WiFi" preferredStyle:UIAlertControllerStyleAlert];
                /* 创建action对象 */
                UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    
                }];
                
                /* alert添加action对象 */
                [alert addAction:actionConfirm];
                
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
                break;
            }
        }
    }];
    
    // 3.开始监控
    [manager startMonitoring];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
